/**
 * 数据字典功能
 */
import * as tools from 'src-ssr/util/common';
import { Sequelize, Op, QueryTypes, where } from 'sequelize';
import models, { sequelize } from 'src-ssr/db/sequelize';
const mysql = require('../db/connect').mysql;

/**
 * 混合字典，即静态的字典内容混合用户输入的内容
 * @returns
 */
export const getHybridDict = async (tid) => {
  const dictionary = await tools.getSystemConfig('dictionary', tid); // 数据字典

  /* const HybridSource = [
    { // 线索来源
      dict: 'clueSource', // 字典项
      model: 'clues', // 关联模型
      field: 'source' // 关联字段
    },
    { // 线索状态
      dict: 'clueStatus',
      model: 'clues',
      field: 'status'
    },
    { // 线索等级
      dict: 'clueRating',
      model: 'clues',
      field: 'rating'
    },
    { // 客户来源
      dict: 'clueSource', // 字典项
      model: 'customers', // 关联模型
      field: 'source' // 关联字段
    },
    { // 客户状态
      dict: 'clueStatus',
      model: 'customers',
      field: 'status'
    },
    { // 客户等级
      dict: 'clueRating',
      model: 'customers',
      field: 'rating'
    },
    { // 客户类型
      dict: 'customerType',
      model: 'customers',
      field: 'type'
    },
    { // 跟进方式
      dict: 'followupWay',
      model: 'followups',
      field: 'way'
    },
    { // 报价阶段
      dict: 'offerStage',
      model: 'offers',
      field: 'stage'
    }
  ];

  for (const item of HybridSource) {
    const data = await models[item.model].findAll({
      attributes: [item.field],
      distinct: true,
      where: {
        [Op.and]: [{
          [item.field]: {
            [Op.notIn]: dictionary[item.dict].map(v => v.value)
          }
        }, {
          [item.field]: {
            [Op.ne]: null
          }
        }, {
          [item.field]: {
            [Op.ne]: ''
          }
        }]
      },
      raw: true
    });
    dictionary[item.dict] = [...dictionary[item.dict], data.map(v => ({ value: v[item.field], label: v[item.field] }))];
  }; */

  return dictionary;
};

/**
 * 动态字典
 * @param {*} reqTypes
 * @param {string} tid 类型 0-系统用户 大于0-租户id
 * @returns
 */
export const getDynamicDict = async (reqTypes, tid) => {
  if (!reqTypes) return {};

  const types = typeof reqTypes === 'string' ? [reqTypes] : reqTypes;

  const dict = {};
  try {
    for (const item of types) {
      switch (item) {
        case 'user':
          dict[item] = await models.m_users.findAll({ attributes: [['id', 'value'], ['nickname', 'label'], 'tel', 'rights', 'state'], where: { tenant_id: tid }, raw: true });
          break;
        case 'tenant':
          dict[item] = await models.m_tenants.findAll({ attributes: [['id', 'value'], ['tenant_name', 'label']], where: { id: { [Op.gt]: 0 }, state: 1 }, raw: true });
          break;
        case 'customer':
          dict[item] = await models.t_customers.findAll({ attributes: [[Sequelize.literal('bin_to_uuid(uid, 1)'), 'value'], ['nickname', 'label']], where: { tenant_id: tid }, raw: true });
          break;
        case 'material':
          dict[item] = await models.t_materials.findAll({
            attributes: [[Sequelize.literal('bin_to_uuid(uid, 1)'), 'value'], ['material_name_model', 'label'], 'material_unit', 'default_image'],
            where: { tenant_id: tid },
            order: [['id', 'desc']],
            raw: true
          });
          break;
        case 'logistics':
          [dict[item]] = await mysql.query(`SELECT logistics value, logistics label
            FROM t_deliveries
            WHERE IFNULL(logistics, '') <> '' AND tenant_id = ?
            GROUP BY logistics
            ORDER BY COUNT(id) DESC`, [tid]);
          break;
      }
    }
  } catch (e) {
    console.log(e);
  }
  return dict;
}

// 刷新数据字典
const refresh = async (tid) => {
  global.dictionary = {};
  global.dictObj = {};

  // 取租户
  let tenants = [];
  if (!tid) {
    tenants = (await models.m_tenants.findAll({ attributes: ['id'], raw: true })).map(v => v.id);
    tenants.push(0);
  } else {
    tenants.push(tid);
  }

  for (const tid of tenants) {
    const dictionary = await getHybridDict(tid); // 数据字典
    const dictObj = {};
    for (const key in dictionary) {
      dictObj[key] = {};
      dictionary[key].forEach(v => {
        dictObj[key][v.value] = Object.assign({}, v);
      });
    }
    global.dictionary[tid] = dictionary;
    global.dictObj[tid] = dictObj;
  }
};

export default { refresh, getHybridDict, getDynamicDict }
